<template>
  <div>
    <el-row type="flex">
      <el-select v-model="searchLabel" placeholder="SKU/OrderID">
        <el-option
          v-for="item in searchOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-if="searchLabel === 'sku' || searchLabel === 'orderNumber'"
        v-model="searchValue"
        style="width:400px"
        clearable
        placeholder="Search"
        prefix-icon="el-icon-search"
        @keyup.enter.native="search"
      />
      <el-input
        v-else
        v-model="searchValue"
        style="width:400px"
        maxlength="50"
        clearable
        placeholder="Search"
        prefix-icon="el-icon-search"
        @keyup.enter.native="search"
      />

      <el-select
        v-model="storeId"
        placeholder="Select Store"
        :loading="storeLoading"
        @change="storeSelected"
        @visible-change="getStore"
      >
        <el-option
          v-for="item in storeOptions"
          :key="item.id"
          :label="storeMap[item.type] + ' - ' + item.name"
          :value="item.id"
        />
      </el-select>

      <el-select
        v-model="dateType"
        placeholder="Filter By Date"
        style="width:150px"
      >
        <el-option
          v-for="item in dateOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-if="dateType"
        v-model="dateValue"
        class="myDatePicker"
        type="daterange"
        align="right"
        value-format="yyyy-MM-dd"
        unlink-panels
        range-separator="to"
        start-placeholder="start date"
        end-placeholder="end date"
        @change="dateSelected"
      />

      <el-select
        v-if="pageName !== 'PACKING' && pageName !== 'UNSHIPPED'"
        v-model="searchCarrierObj.freightId"
        placeholder="Select Carrier"
        @visible-change="freightList"
        @change="fatherInit"
      >
        <el-option
          v-for="item in freightOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-else
        v-model="searchCarrierObj.otherLogisticsId"
        placeholder="Select Carrier"
        @visible-change="logisticsList"
        @change="fatherInit"
      >
        <el-option
          v-for="item in otherLogisticsOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>

      <el-button @click="toSelectCountry">Countries</el-button>

      <!-- 选择国家弹窗 -->
      <choose-country
        v-if="countryVisible"
        @closeChooseCountry="closeChooseCountry"
      />
    </el-row>
    <div
      v-if="
        searchedData.length ||
          (storeId && storeId !== -1) ||
          (dateObj.dateField && dateObj.beginDate && dateObj.endDate) ||
          checkedCountryRes.length ||
          searchCarrierObj.freightId > 0 ||
          searchCarrierObj.otherLogisticsId > 0
      "
      class="filterRes"
    >
      <div
        v-for="(item, index) in searchedData"
        :key="index"
        class="filterItem"
      >
        <span class="title">
          {{ matchVal(item.label) }}
        </span>
        <el-tag closable @close="closeTag(item.label)">
          {{ item.value }}
        </el-tag>
      </div>

      <!-- 已选择店铺 -->
      <div v-if="storeId && storeId !== -1" class="filterItem">
        <span class="title">Store Name:</span>
        <el-tag closable @close="closeTag('store')">
          {{ storesMap[storeId] }}
        </el-tag>
      </div>

      <div
        v-if="dateObj.dateField && dateObj.beginDate && dateObj.endDate"
        class="filterItem"
      >
        <span class="title">
          {{ dateObj.dateField }}
        </span>
        <el-tag closable @close="closeTag('date')">
          {{ dateObj.beginDate }} - {{ dateObj.endDate }}
        </el-tag>
      </div>

      <div v-if="searchCarrierObj.freightId" class="filterItem">
        <span class="title">Logistics Name:</span>
        <el-tag closable @close="closeTag('freightId')">
          {{ freightMap[searchCarrierObj.freightId] }}
        </el-tag>
      </div>

      <div v-if="searchCarrierObj.otherLogisticsId" class="filterItem">
        <span class="title">Logistics Name:</span>
        <el-tag closable @close="closeTag('otherLogisticsId')">
          {{ otherLogisticsMap[searchCarrierObj.otherLogisticsId] }}
        </el-tag>
      </div>

      <div v-if="checkedCountryRes.length" class="filterItem">
        <span class="title">Countries:</span>
        <el-tag
          v-for="(item, index) in checkedCountryRes"
          :key="index"
          closable
          @close="closeTag('country', index)"
        >
          {{ cloneCountryMap['countryMap'][item] }}
        </el-tag>
      </div>

      <el-button
        type="danger"
        size="mini"
        @click="emptyFilter"
      ><i class="el-icon-delete" /> Empty</el-button>
    </div>
  </div>
</template>

<script>
import { freightList } from '@/api/common';
import { logisticsList } from '@/api/logistics';
import { authorizedList } from '@/api/authorized';
import ChooseCountry from './chooseCountry';
export default {
  inject: ['cloneCountryMap'],
  components: {
    ChooseCountry
  },
  props: {
    pageName: {
      type: String,
      required: true
    },
    searchParams: {
      type: Object,
      default: () => ({})
    },
    store: {
      type: Object,
      required: true
    },
    dateObj: {
      type: Object,
      required: true
    },
    searchCarrierObj: {
      type: Object,
      required: true
    },
    fatherInit: {
      type: Function,
      required: true
    },
    checkedCountryRes: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      searchOptions: [
        {
          value: 'sku',
          label: 'SKU'
        },
        {
          value: 'orderNumber',
          label: 'Order Number'
        },
        {
          value: 'orderNumberPrefix',
          label: 'OrderNumberPrefix'
        },
        {
          value: 'consigneeName',
          label: 'Consignee Name'
        }
      ],
      searchLabel: '',
      searchValue: '',
      searchedData: [], // 输入框搜索条件集合
      storeId: this.store.id > 0 ? this.store.id : null,
      storeLoading: false,
      storeOptions: [],
      storeMap: {
        1: 'shopify',
        2: 'wooc',
        4: 'custom'
      },
      storesMap: {},
      dateType: '',
      dateValue: '',
      dateOptions: [
        {
          label: 'Payment At',
          value: 'paymentTime',
          disabled: []
        },
        {
          label: 'Submit At',
          value: 'submitTime',
          disabled: []
        },
        {
          label: 'PlateMaking At',
          value: 'platemakingTime',
          disabled: []
        },
        {
          label: 'Print At',
          value: 'printTime',
          disabled: []
        },
        {
          label: 'Shipped At',
          value: 'shippedTime',
          disabled: []
        },
        {
          label: 'Delivery At',
          value: 'deliveryTime',
          disabled: []
        }
      ],
      countryVisible: false,
      freightMap: {},
      freightOptions: [],
      otherLogisticsMap: {},
      otherLogisticsOptions: []
    };
  },
  watch: {
    searchParams: {
      deep: true,
      handler: function(newV, oldV) {
        if (Object.keys(newV).length > this.searchedData.length) {
          const arr = this.searchedData.map((item) => item.label);
          for (var k in newV) {
            const index = arr.indexOf(k);
            if (index > -1) {
              this.searchedData[index].value = newV[k];
            } else {
              const obj = {
                label: k,
                value: newV[k]
              };
              this.searchedData.push(obj);
            }
          }
        }
      }
    },
    store: {
      deep: true,
      handler: function(newV, oldV) {
        if (newV.id > 0) {
          authorizedList({ storeType: 'VIRTUAL' }).then((res) => {
            const obj = {};
            res.data.forEach((item) => {
              obj[item.id] = item.name;
            });
            this.storeOptions = res.data;
            this.storesMap = obj;
            this.storeId = newV.id;
          });
        } else {
          this.storeId = null;
        }
      }
    },
    searchCarrierObj: {
      deep: true,
      handler: function(newV, oldV) {
        if (newV.freightId > 0) {
          freightList().then((res) => {
            this.freightOptions = res.data || [];
            const obj = {};
            res.data.forEach((item) => {
              obj[item.id] = item.name;
            });
            this.freightMap = obj;
          });
        }
        if (newV.otherLogisticsId > 0) {
          logisticsList().then((res) => {
            this.otherLogisticsOptions = res.data || [];
            const obj = {};
            res.data.forEach((item) => {
              obj[item.id] = item.name;
            });
            this.otherLogisticsMap = obj;
          });
        }
      }
    }
  },
  created() {
    // 店铺列表进入订单页面，传递参数
    authorizedList({ storeType: 'VIRTUAL' }).then((res) => {
      this.storeOptions = res.data;
      const obj = {};
      res.data.forEach((item) => {
        obj[item.id] = item.name;
      });
      this.storesMap = obj;
      if (this.$route.params.storeId) {
        this.store.id = this.$route.params.storeId || 0;
      }
    });
  },
  methods: {
    dateSelected(selectVal) {
      // 选择日期后更新数据
      this.$set(this.dateObj, 'dateField', this.dateType);
      this.$set(this.dateObj, 'beginDate', selectVal ? selectVal[0] : '');
      this.$set(this.dateObj, 'endDate', selectVal ? selectVal[1] : '');
      this.fatherInit(1);
    },
    search() {
      if (!this.searchLabel || !this.searchValue.trim()) {
        this.fatherInit(1);
        return;
      }
      const obj = {};
      obj['label'] = this.searchLabel;
      obj['value'] = this.searchValue;
      if (this.searchedData.length) {
        var repeat = false;
        var change = false;
        this.searchedData.forEach((item, index) => {
          if (item.label === obj.label) {
            if (item.value !== obj.value) {
              change = true;
              this.searchedData[index].value = obj.value;
            } else {
              repeat = true;
            }
          }
        });
        if (repeat) {
          return this.$message.warning(
            'The value is repeated. Please re-enter'
          );
        } else {
          if (!change) {
            this.searchedData.push(obj);
          }
        }
      } else {
        this.searchedData.push(obj);
      }
      switch (this.searchLabel) {
        case 'orderNumber':
          this.searchParams['orderNumber'] = this.searchValue.trim();
          break;
        case 'orderNumberPrefix':
          this.searchParams['orderNumberPrefix'] = this.searchValue.trim();
          break;
        case 'sku':
          this.searchParams['sku'] = this.searchValue.trim();
          break;
        case 'consigneeName':
          this.searchParams['consigneeName'] = this.searchValue.trim();
          break;
      }
      this.searchValue = '';
      this.searchLabel = '';
      this.fatherInit();
    },
    matchVal(value) {
      var str = '';
      this.searchOptions.forEach((item) => {
        if (item.value === value) {
          str = item.label;
          return;
        }
      });
      return str;
    },
    storeSelected(selectVal) {
      // 已选择平台
      this.$set(this.store, 'id', selectVal);
      this.fatherInit(true);
    },
    getStore(val) {
      if (val) {
        this.storeLoading = true;
        const params = {
          storeType: 'VIRTUAL'
        };
        authorizedList(params).then((res) => {
          this.storeLoading = false;
          this.storeOptions = res.data;
        });
      }
    },
    freightList(val) {
      if (val) {
        freightList().then((res) => {
          this.freightOptions = res.data || [];
        });
      }
    },
    logisticsList(val) {
      if (val) {
        logisticsList().then((res) => {
          this.otherLogisticsOptions = res.data || [];
        });
      }
    },
    toSelectCountry() {
      this.countryVisible = true;
    },
    closeChooseCountry() {
      this.countryVisible = false;
    },
    closeTag(type, index) {
      // 关闭检索标签
      if (type === 'country') {
        this.checkedCountryRes.splice(index, 1);
      } else if (type === 'date') {
        this.dateType = '';
        this.dateValue = '';
        this.$set(this.dateObj, 'dateField', '');
        this.$set(this.dateObj, 'beginDate', '');
        this.$set(this.dateObj, 'endDate', '');
      } else if (type === 'store') {
        this.storeId = null;
        this.$set(this.store, 'id', -1);
      } else if (type === 'freightId' || type === 'otherLogisticsId') {
        this.$emit('emptyCarrier');
      } else {
        if (type === 'sku') {
          delete this.searchParams.sku;
        } else if (type === 'consigneeName') {
          delete this.searchParams.consigneeName;
        } else if (type === 'orderNumber') {
          delete this.searchParams.orderNumber;
        } else if (type === 'orderNumberPrefix') {
          delete this.searchParams.orderNumberPrefix;
        } else if (type === 'waybill') {
          delete this.searchParams.waybill;
        }
        this.spliceSearchedData(type);
      }
      this.fatherInit(1);
    },
    spliceSearchedData(type) {
      this.searchedData.forEach((item, index) => {
        if (item.label === type) {
          this.searchedData.splice(index, 1);
          return;
        }
      });
    },
    emptyFilter() {
      this.dateType = '';
      this.dateValue = '';
      this.searchedData = [];
      this.storeId = null;
      this.$emit('emptyFilter');
    }
  }
};
</script>
<style lang="scss" scoped>
.el-select,
.el-button,
.el-input,
.el-date-editor {
  margin-right: 10px;
}
.el-select {
  width: 150px;
}
.filterRes {
  position: relative;
  background-color: #f2f2f2;
  margin-top: 5px;
  padding-right: 95px;
  padding-top: 4px;
  .filterItem {
    padding-top: 2px;
    padding-bottom: 2px;
    padding-left: 10px;
    .title {
      display: inline-block;
      font-size: 12px;
      width: 110px;
    }
    .el-tag {
      margin-right: 10px;
      margin-bottom: 4px;
    }
  }
  .el-button {
    position: absolute;
    top: 10px;
    right: 20px;
    padding: 3px 7px;
  }
}
</style>
